<script setup>
import {
    Download,
    Delete,
    Edit
} from '@element-plus/icons-vue'
import { ref, computed,watchEffect,onUnmounted } from 'vue'
import dayjs from 'dayjs';
import { useExamStore } from '@/stores/examStore'; 
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
dayjs.extend(utc);  
dayjs.extend(timezone);
import { useRouter } from 'vue-router';

const router = useRouter();

// 存储当前选中的考试数据
const currentExam = ref({});
let isUpdating = ref(false); 
// 定义考试数据模型
const examData = ref([
    {
    e_id: 1,         // 考试 ID（新增考试时为空）
    e_name: '',         // 考试名称
    startTime: null,    // 考试开始时间
    endTime: null,      // 考试结束时间
    to_endTime: null,   //距离结束的时间
    e_autostart: 0, // 是否自动开始
    fileBase64: '',
    fileName: '',  
    total: '',
    status: '',       // 试卷名称
}]);

const page = ref({
    pageNum: 1, //当前页
    pageSize: 5, //每页条数
})

// 考试表单校验规则
const examRules = {
    e_name: [
        { required: true, message: '请输入考试名称', trigger: 'blur' },
    ],
    startTime: [
        { required: true, message: '请选择开始时间', trigger: 'blur' },
    ],
    endTime: [
        { required: true, message: '请选择结束时间', trigger: 'blur' },
    ],
};

const formatDate=(dateString) =>{
    return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
    }

// 根据考试状态设置字体样式
const getStatusClass = (status) => {
    switch (status) {
        case "未开始":
            return "status-blue";
        case "进行中":
            return "status-green";
        case "已结束":
            return "status-red";
        default:
            return "";
    }
};



// 搜索表单数据
const searchForm = ref({
    e_name: '',
    e_starttime: null,
    e_stoptime: null,
    e_autostart: 0,
});


// 重置表单方法
const resetForm = () => {
    searchForm.value = {
        e_name: '',
        e_starttime: null,
        e_stoptime: null,
        e_autostart: 0
    };
    examList();
};



// 打包下载方法
const downloadZip = (id, name) => {
    console.log('下载考试 ID:', id, '名称:', name);
    // 补充下载逻辑
};


import { examListService, examAddService, examDeleteService ,examSearchService,examUpdateStatusService} from '@/api/exam.js'


const searchExam =async ()=>{
    const { e_name, startTime, endTime,e_autostart } = searchForm.value;
    let params = {
        pageNum: page.value.pageNum,
        pageSize: page.value.pageSize,
    }

    
    if (!e_name || e_name.trim() === '') {
    ElMessage.error('考试名称不能为空');
    return;
  }
  if ((startTime && endTime)&&(new Date(endTime) < new Date(startTime))) {
    ElMessage.error('结束时间不能早于开始时间');
    return;
  }

  const examSearch = {
            examName: e_name,
            beginTime: startTime,
            endTime: endTime,
            auto: e_autostart,
        };
        try{  
    let result = await examSearchService(examSearch,params);
    examData.value = result.data.list.map(item => ({
            e_id: item.id,
            e_name: item.examName,  // 映射examName到e_name
            startTime: item.beginTime,  // 映射beginTime到startTime
            endTime: item.endTime,
            status: item.status,
            fileName: item.fileName,
            fileBase64: item.fileBase64,
            e_autostart: item.auto,
            to_endTime: calculateTimeRemaining(item.endTime, item.beginTime,item.status,item.id),  
        }));
    examData.value.total=result.data.total;
    }catch(error){
        console.error('Error in exam list request:', error);
    }

};


// 删除考试方法
const removeExam = (id) => {
    examDeleteService(id)
    .then(() => {
      ElMessage.success('删除考试成功');
      examList();
    })
    .catch(() => {
      ElMessage.error('删除考试失败');
    });
    
};

const formatToLocalDateTime=(date)=> {
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false, // 使用 24 小时制
    }).replace(/(\d{4})\/(\d{2})\/(\d{2}) (\d{2}):(\d{2}):(\d{2})/, '$1-$2-$3T$4:$5:$6');
}

// 新增考试方法
const addExam = () => {
    const { e_name, startTime, endTime,e_autostart } = searchForm.value;

    if (!e_name || e_name.trim() === '') {
    ElMessage.error('考试名称不能为空');
    return;
  }
  if (!startTime || !endTime) {
    ElMessage.error('开始时间和结束时间不能为空');
    return;
  }
  
     const startTimeDate = new Date(startTime);
    const endTimeDate = new Date(endTime);

  if (endTimeDate < startTimeDate) {
    ElMessage.error('结束时间不能早于开始时间');
    return;
  }

    const formattedStartTime = formatToLocalDateTime(startTimeDate);
    const formattedEndTime = formatToLocalDateTime(endTimeDate);


  const examCreate = {
            examName: e_name,
            beginTime: formattedStartTime,
            endTime: formattedEndTime,
            auto: e_autostart,
        };
       
  // 调用后端接口新增考试信息
  examAddService(examCreate)
    .then(() => {
      ElMessage.success('新增考试成功');
      examList();
    })
    .catch(() => {
      ElMessage.error('新增考试失败');
    });

};

const examStore = useExamStore();
const handleRowClick = (row) => {
    examStore.setCurrentExam(row);
  router.push({ path: '/teacher/examEdit' });
};

// 定义响应式数据
const selectedFile = ref(null);
const fileUrl = ref('');



onUnmounted(() => {
  if (fileUrl.value) {
    URL.revokeObjectURL(fileUrl.value);
  }
});

//列出考试列表

//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    page.value.pageNum = num
    examList();
}


const calculateTimeRemaining = (endTime,startTime,status,id) => {
    // 获取当前时间
    const currentTime = new Date();

    // 将结束时间转换为 Date 对象
    const endDate = new Date(endTime);
    
    const startDate = new Date(startTime);

    // 计算时间差，返回的是毫秒数
    const timeDiff = endDate - currentTime;

    if (timeDiff <= 0) {
        return "已结束";  // 如果结束时间小于当前时间，说明考试已经结束
    }
    if(currentTime<startDate){
        return "未开始";
    }

    if (status === "未开始" &&! isUpdating.value &&id !== undefined) {
        handleExamUpdate(id)
        examList();
    }

    // 计算剩余天数、小时数、分钟数和秒数
    const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
    const hours = Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000);

    // 返回格式化的时间
    return `${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`;
};



// 确保这是一个异步函数
const  handleExamUpdate= async (id) =>{
    isUpdating.value = true;
        try {
            // 使用 await 等待异步请求完成
            await examUpdateStatusService(id);
        } catch (error) {
            console.error('更新考试状态失败', error);
        } finally {
            isUpdating.value = false; // 请求完成后恢复标志位，允许下次执行
    }
}







//列出考试列表
const examList = async () => {
    let params = {
        pageNum: page.value.pageNum,
        pageSize: page.value.pageSize,
    }
    try{  
    let result = await examListService(params);
    examData.value = result.data.list.map(item => ({
            e_id: item.id,
            e_name: item.examName,  // 映射examName到e_name
            startTime: item.beginTime,  // 映射beginTime到startTime
            endTime: item.endTime,
            status: item.status,
            fileName: item.fileName,
            fileBase64: item.fileBase64,
            e_autostart: item.auto,
            to_endTime: calculateTimeRemaining(item.endTime, item.beginTime,item.status,item.id),  
        }));
    examData.value.total=result.data.total;

     
    }catch(error){
        console.error('Error in exam list request:', error);
    }
}
examList();

// 调用 examList 获取数据并启动倒计时
examList().then(() => {
    startCountdown();  // 启动定时器
});

const startCountdown = () => {
    const updateCountdown = () => {
        examData.value.forEach(item => {
            item.to_endTime = calculateTimeRemaining(item.endTime, item.startTime,item.status,item.id);
        });
        requestAnimationFrame(updateCountdown); // 下一帧继续更新
    };
    updateCountdown(); // 启动循环
};
const getDownloadUrl = (base64Data) => {
      const byteCharacters = atob(base64Data);
      const byteNumbers = new Array(byteCharacters.length);
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
      }
      const byteArray = new Uint8Array(byteNumbers);
      const blob = new Blob([byteArray], { type: 'application/octet-stream' });
      return URL.createObjectURL(blob);
    };

//调用接口,添加表单
import { ElMessage,ElPagination } from 'element-plus'


//定义变量,控制标题的展示
const title = ref('')


</script>


<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>考试管理</span>
            </div>
        </template>

        <!-- 根据考试名称查询某场考试or新增考试信息 -->
        <el-form :model="searchForm" inline style="margin-bottom: 20px">
            <el-form-item label="考试名称">
                <el-input v-model="searchForm.e_name" placeholder="请输入考试名称" clearable />
            </el-form-item>
            <el-form-item label="开始时间">
                <el-date-picker v-model="searchForm.startTime" type="datetime" placeholder="选择开始时间" ></el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间">
                <el-date-picker v-model="searchForm.endTime" type="datetime" placeholder="选择结束时间" ></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-checkbox v-model="searchForm.e_autostart" true-label="1" false-label="0">自动开始</el-checkbox>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="searchExam">查询</el-button>
                <el-button type="default" icon="RefreshLeft" @click="resetForm">重置</el-button>
                <el-button type="success" icon="Plus" @click="addExam">新增考试</el-button>
            </el-form-item>
        </el-form>

        <!-- 考试列表 -->
        <el-table :data="examData" style="width: 100%" @row-click="handleRowClick">
            <el-table-column label="名称">
                <template #default="{ row }">{{ row.e_name }}</template>
            </el-table-column>
            <el-table-column label="开始时间">
                <template #default="{ row }">{{ formatDate(row.startTime) }}</template>
            </el-table-column>
            <el-table-column label="结束时间">
                <template #default="{ row }">{{ formatDate(row.endTime) }}</template>
            </el-table-column>
            <el-table-column label="距离结束时间">
                <template #default="{ row }">{{ row.to_endTime }}</template>
            </el-table-column>
            <el-table-column label="试卷">
                <template #default="{ row }">
                <div v-if="row.fileBase64">
                <a  @click.stop :href="getDownloadUrl(row.fileBase64)" :download="row.fileName" class="file-link">
                    {{ row.fileName }}
                 </a>
                </div>
                <div v-else>
                 <span>暂无文件</span>
             </div>
            </template>
            </el-table-column>
            <el-table-column label="自动开始">
                <template #default="{ row }">{{ row.e_autostart === 1 ? '是' : '否' }}</template>
            </el-table-column>
            <el-table-column label="考试状态">
                <template #default="{ row }">
                    <span :class="getStatusClass(row.status)">
                        {{ row.status }}
                    </span>
                </template>
            </el-table-column>
            
            <el-table-column label="删除考试">
                <template #default="{ row }">
                    <el-button :icon="Delete" circle plain type="danger" @click.stop="removeExam(row.e_id)"></el-button>
                </template>
            </el-table-column>

            <template #empty>
                <el-empty description="没有考试数据" />
            </template>
        </el-table>
        <div class="pagination-container">
            <el-pagination
                background
                layout="total, prev, pager, next, jumper"
                :total="examData.total"
                :page-size.sync="page.pageSize"
                :current-page.sync="page.pageNum"
                @current-change="onCurrentChange"
            />
            <span class="fixed-size-info">每页5条</span>
        </div>

    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .el-form-item {
        margin-bottom: 10px;
    }

    .status-blue {
        color: rgb(26, 154, 214);
    }

    .status-green {
        color: rgb(26, 223, 118);
    }

    .status-red {
        color: rgb(234, 15, 15);
    }
    .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;  /* 居中对齐 */
    align-items: center;      /* 垂直居中对齐 */
}

.fixed-size-info {
    margin-left: 16px;
    font-size: 14px;
    color: #606266; 
    display: inline-block;  /* 确保它和分页控件在同一行 */
}
}
</style>